package com.elitesland.metadata.rest;

import com.elitesland.core.base.ApiCode;
import com.elitesland.core.base.ApiResult;
import com.elitesland.core.base.PagingVO;
import com.elitesland.core.exception.BusinessException;
import com.elitesland.metadata.param.MetaFieldQParam;
import com.elitesland.metadata.param.MetaFieldSaveParam;
import com.elitesland.metadata.service.MetaFieldService;
import com.elitesland.metadata.vo.MetaFieldVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.CompletableFuture;

/**
 * <pre>作用说明</pre>
 *
 * @author mir
 * @date 11/21/2020 12:12 PM
 */
@RestController
@RequestMapping("/meta/fields")
@Api(value = "元数据字段管理", tags = {"元数据字段管理"})
public class MetaFieldController {

    private MetaFieldService metaFieldService;

    @Autowired
    public void setMetaFieldService(MetaFieldService metaFieldService) {
        this.metaFieldService = metaFieldService;
    }

    @PostMapping("/q")
    @ApiOperation("检索元数据字段信息")
    public CompletableFuture<ApiResult<PagingVO<MetaFieldVO>>> search(@RequestBody MetaFieldQParam param) {
        return metaFieldService.search(param)
                .thenApply(ApiResult::ok);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据记录ID返回对应的元数据字段信息")
    public CompletableFuture<ApiResult<MetaFieldVO>> oneById(@PathVariable Long id) {
        return metaFieldService.oneById(id)
                .thenApply(f -> f.map(ApiResult::ok)
                        .orElse(ApiResult.fail(ApiCode.NOT_FOUND)));
    }

    @PostMapping
    @ApiOperation("添加元数据字段信息")
    public CompletableFuture<ApiResult<Long>> create(@RequestBody MetaFieldSaveParam saveParam) {
        return metaFieldService.create(saveParam).thenApply(ApiResult::ok);
    }

    @PutMapping
    @ApiOperation("修改元数据字段信息")
    public CompletableFuture<ApiResult<Object>> update(@RequestBody MetaFieldSaveParam saveParam) {
        return CompletableFuture.supplyAsync(() -> {
            metaFieldService.update(saveParam);

            return ApiResult.ok();
        })
                .exceptionally(ex -> {
                    val e = (BusinessException) ex.getCause();
                    return ApiResult.fail(e.getCode() == null ? ApiCode.FAIL : e.getCode(), e.getMessage());
                });
    }

    @DeleteMapping("/{id}")
    @ApiOperation("根据记录ID删除对应的元数据字段信息")
    public ApiResult<Object> removeById(@PathVariable Long id) {
        CompletableFuture.runAsync(() -> metaFieldService.removeById(id));
        return ApiResult.ok();
    }
}
